<template>
  <div class="bx--grid bx--grid--full-width bx--grid--no-gutter test-page">
    <div class="bx--row">
      <div class="bx--col-lg-16">    
            <h1>TestPage3</h1>
      </div>
    </div>    
    <cv-form>
      <div class="bx--row">
        <div class="bx--col-lg-16">   
          <cv-file-uploader
            :kind="kind"
            :label="label"
            :helperText="helperText"
            :drop-target-label="dropTargetLabel"
            :accept="accept"
            :clear-on-reselect="clearOnReselect"
            :initial-state-uploading="initialStateUploading"
            :removable="removable"
            @change="changeFile('uploader',$event)" :files="storyFiles" :clearOnReselect="clearOnReselect"
            :remove-aria-label="removeAriaLabel" ref="fileUploader">
          </cv-file-uploader>  
        </div>
      </div>

      <div class="bx--row">
        <div class="bx--col-lg-12">  
          <label class="bx--label"><strong class="bx--file--label">(Sample2)File chooser</strong></label> <input type="file" ref="file" :accept="accept" @change="changeFile('file',$event)"> 
        </div>
                
        <div class="bx--col-lg-4" style="display: flex; justify-content: flex-end"> 
          <cv-button type="button" kind="primary" :small="true" @click="doFormat('format')">Format</cv-button>&nbsp;
          <cv-button type="button" kind="primary" :small="true" @click="doFormat('compress')">Compress</cv-button>
          <cv-button type="button" kind="primary" :small="true" @click="doFormat('clear')">Clear</cv-button>
        </div>
      </div>

      <div class="bx--row">
        <div class="bx--col-lg-12">
          <span style="color:red">{{errMsg}}</span>
        </div>
      </div>      
      <div class="bx--row">
        <div class="bx--col-lg-16">      
            <ace-editor v-model="content" @init="editorInit" :lang="lang" theme="chrome" width="100%" height="30rem"></ace-editor>          
        </div>
      </div>

    </cv-form>
    <cv-loading :active="loading" :overlay="true"></cv-loading>
  </div>
</template>

<script>
import XLSX from "xlsx";
const jsonObj={"login":"IBM","id":1459110,"node_id":"MDEyOk9yZ2FuaXphdGlvbjE0NTkxMTA=","url":"https://api.github.com/orgs/IBM","repos_url":"https://api.github.com/orgs/IBM/repos","events_url":"https://api.github.com/orgs/IBM/events","hooks_url":"https://api.github.com/orgs/IBM/hooks","issues_url":"https://api.github.com/orgs/IBM/issues","members_url":"https://api.github.com/orgs/IBM/members{/member}","public_members_url":"https://api.github.com/orgs/IBM/public_members{/member}","avatar_url":"https://avatars0.githubusercontent.com/u/1459110?v=4","description":"","name":"International Business Machines","company":null,"blog":"https://www.ibm.com/opensource/","location":"Armonk, New York, U.S.","email":null,"twitter_username":null,"is_verified":false,"has_organization_projects":true,"has_repository_projects":true,"public_repos":1794,"public_gists":0,"followers":0,"following":0,"html_url":"https://github.com/IBM","created_at":"2012-02-21T22:13:01Z","updated_at":"2020-10-19T14:28:02Z","type":"Organization"};
export default {
  name: 'TestPage2',
  components: {
    "ace-editor": require("vue2-ace-editor"),
  },
  data() {
    return {
      loading:false,
      errMsg:"",
      content:JSON.stringify(jsonObj),
      lang:"json",

      "kind": "button",
      "label": "(Sample1)File uploader",
      "helperText": "Select the files you want to upload",
      "dropTargetLabel": "",
      "use_dropTargetSlot": false,
      "accept": ".txt,.xlsx,.xls",
      "clearOnReselect": false,
      "initialStateUploading": false,
      "removable": true,
      "removeAriaLabel": "Custom remove aria label",
      "clearOnReselect":true,
      storyFiles:[],
    };
  },
  methods: {
    editorInit() {
      require("brace/ext/language_tools"); 
      require("brace/mode/html");
      require("brace/mode/json");
      require("brace/mode/java");
      require("brace/mode/javascript");
      require("brace/mode/python");
      // require("brace/theme/tomorrow_night_blue");
      require("brace/theme/chrome");
      require("brace/snippets/javascript");
      require("brace/snippets/json");
      require("brace/snippets/java");
      require("brace/snippets/python");
    },     
    doFormat(action){
      try{
        this.errMsg="";        
        if(action==="format"){
          let jsonData=JSON.parse(this.content);
          this.content=JSON.stringify(jsonData,null,4);
        }else if(action==="compress"){
          let jsonData=JSON.parse(this.content);
          this.content=JSON.stringify(jsonData,null,0);
        }else{
          this.content="";
        }
      }catch(err){
        this.errMsg=err;
      }
      
    },
    changeFile(type,e){
      if (typeof FileReader === "undefined") {
        alert("您的浏览器不支持FileReader接口");
        return;
      }

      this.doFormat("clear");    
      let files=[];
      if(type==="uploader"){
        let internalFiles=e;
        internalFiles.forEach(item => files.push(item.file))        
      }else{
        files=e.target.files;
      }
      console.log("files:",files.length);

      if(files.length<=0){//如果没有文件名
        return false;
      }else if(/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){
        console.log("readExcel");
        this.lang="json";
        this.readExcel(files[0]);
      }else if(/\.(txt)$/.test(files[0].name.toLowerCase())){
        console.log("readTextFile");
        this.lang="text";
        this.readTextFile(files[0]);
      }else{        
        alert('上传格式不正确，请上传txt,xls或者xlsx格式');
        return false;        
      }         
    },
    readTextFile(file){
      let self=this;      
      const reader = new FileReader();            
	    reader.onloadend = function(e){
	        self.content=e.target.result;
      };
      // reader.readAsText(file,"utf-8");  
      reader.readAsText(file);      
    },
    readExcel(file) {//表格导入-https://blog.csdn.net/liyi_mowu/article/details/84768140
        let self=this;            
        const fileReader = new FileReader();
        fileReader.onload = (ev) => {
        try {
            const data = ev.target.result;
            const workbook = XLSX.read(data, {
              type: 'binary'
            });
            const wsname = workbook.SheetNames[0];//取第一张表
            const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);//生成json表格内容
            console.log(ws);
            self.content=JSON.stringify(ws,null,4); 
            // that.outputs = [];//清空接收数据
            // //编辑数据
            // for(var i= 0;i<ws.length;i++){
            // var sheetData = {
            //     address: ws[i].addr,
            //     value: ws[i].value
            // }
            // that.outputs.push(sheetData);
            // }
            // this.$refs.upload.value = '';    
        } catch (e) {    
            return false;
        }
        };
        fileReader.readAsBinaryString(file);
    }
  },  
  computed: {
    paramData(){
      let data={};
      data.id=this.$route.params["id"];
      return data;
    }     
  },
  mounted(){
  } 
};
</script>

<style lang="scss" scoped>
@import '../../styles/carbon-utils';
/deep/ .bx--modal-footer .cv-button{
  justify-content: center;
  align-items: center;
  width:100%;
}
</style>